package cn.growthgate.fgo.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.ArrayUtils;

/**
 * url工具类
 * 
 * @author GrowthGate
 * @since 2019年4月2日
 *
 */
public class UrlUtils {

	private static final String CHARSET = "UTF-8";

	/**
	 * 添加url参数
	 * @param url
	 * @param map
	 * @return
	 */
	public static String addParams(String url, Map<String, String[]> map) {
		if (CollectionUtils.isEmpty(map)) {
			return url;
		}
		String params = mapToStringParams(map);
		return url.contains("?") ? url + "&" + params : url + "?" + params;
	}
	
	/**
	 * 将map转化为url参数
	 * @param map
	 * @return
	 */
	public static String mapToStringParams(Map<String, String[]> map) {
		if (CollectionUtils.isEmpty(map)) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String[]> entry : map.entrySet()) {
			if (StringUtils.isNotBlank(entry.getKey()) && ArrayUtils.isNotEmpty(entry.getValue())) {
				String key = entry.getKey();
				for (String value : entry.getValue()) {
					if (ArrayUtils.isNotEmpty(entry.getValue())) {
						sb.append(key).append('=').append(value).append('&');
					}
				}
			}
		}
		if (sb.charAt(sb.length() - 1) == '&') {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}
	
	/**
	 * url编码
	 * @param url
	 * @return
	 */
	public static String encode(String url) {
		try {
			return URLEncoder.encode(url, CHARSET);
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}

	/**
	 * url解码
	 * @param url
	 * @return
	 */
	public static String decode(String url) {
		try {
			return URLDecoder.decode(url, CHARSET);
		} catch (UnsupportedEncodingException e) {
			return url;
		}
	}
	
}
